package go_snowflake

import (
	"errors"
	"sync"
	"time"
)

type SnowflakeID struct {
	mutex     sync.Mutex
	timestamp int64 // 上次生成ID的时间戳
	workerId  int64 // 机器ID
	sequence  int64 // 序列号
	lastSeq   int64 // 上次序列号
}

func (s *SnowflakeID) NextID() (int64, error) {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	// 获取当前时间戳
	now := time.Now().UnixNano() / 1000000

	// 检测时钟回拨
	if now < s.timestamp {
		// 时钟回拨处理逻辑
		waitTime := s.timestamp - now
		if waitTime < 5 { // 回拨小于5ms，等待
			time.Sleep(time.Duration(waitTime) * time.Millisecond)
			now = s.timestamp
		} else {
			// 回拨较大，返回错误或使用备用方案
			return 0, errors.New("时钟回拨过大")
		}
	}

	// 处理序列号
	if now == s.timestamp {
		s.sequence = (s.sequence + 1) & 4095 // 4095 = 2^12 - 1
		if s.sequence == 0 {                 // 序列号溢出
			// 阻塞到下一毫秒
			for now <= s.timestamp {
				now = time.Now().UnixNano() / 1000000
			}
		}
	} else {
		s.sequence = 0 // 新的毫秒，序列号重置
	}

	s.timestamp = now

	// 拼接ID的各部分 (简化版)
	id := (now << 22) | (s.workerId << 12) | s.sequence
	return id, nil
}
